package io.renren.modules.app.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * @author 40938
 * @description lucky
 * @history <TABLE id="HistoryTable" border="1">
 * <TR>
 * <TD>时间</TD>
 * <TD>描述</TD>
 * <TD>作者</TD>
 * </TR>
 * <TR>
 * <TD>2019年5月25日</TD>
 * <TD>version2.0</TD>
 * <TD>40938</TD>
 * </TR>
 * </TABLE>
 */
public class StringUtils {

    // length用户要求产生字符串的长度
    public static String getRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    /**
     * 获取接近值
     *
     * @param x
     * @param src
     * @return
     */
    private static int getApproximate(int x, int[] src) {
        if (src == null) {
            return -1;
        }
        if (src.length == 1) {
            return src[0];
        }
        int minDifference = Math.abs(src[0] - x);
        int minIndex = 0;
        for (int i = 1; i < src.length; i++) {
            int temp = Math.abs(src[i] - x);
            if (temp < minDifference) {
                minIndex = i;
                minDifference = temp;
            }
        }
        return src[minIndex];
    }

    /**
     * @MethodName: 微信获取signature转码方法
     * @Description: TODO
     * @Param: [str]
     * @Return: java.lang.String
     * @Author: 泉哥倍儿帅
     * @Date: 2019/11/1
     **/
    public static String SHA1(String str) {
        try {
            MessageDigest digest = java.security.MessageDigest
                    .getInstance("SHA-1"); //如果是SHA加密只需要将"SHA-1"改成"SHA"即可
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexStr = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexStr.append(0);
                }
                hexStr.append(shaHex);
            }
            return hexStr.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 判断字符串是否全数字
     *
     * @param str
     * @return
     */
    public static boolean isNumericZidai(String str) {
        for (int i = 0; i < str.length(); i++) {
            System.out.println(str.charAt(i));
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }

}

/**
 * Copyright © 2019,傲视幻科 All rights reserved.
 */